<template>
	<div class="category commodity" @click="closeSearch">
		<Navbar></Navbar>
		<svg width="30" height="30" class="next" @click="nextProduct">
			<use xlink:href="#right" v-if="dialogVisible&&index!=categoryList.data.length-1" />
		</svg>
		<svg width="30" height="30" class="prev" @click="prevProduct">
			<use xlink:href="#left" v-if="dialogVisible&&index!=0" />
		</svg>
		<!--.................查看商品详情....................-->
		<el-dialog :visible.sync="dialogVisible" size="small" :close-on-click-modal="false" custom-class="checkBox" :show-close="false" class="check">
			<svg width="26" height="26" class="closebox" @click="dialogVisible = false">
				<use xlink:href="#close" />
			</svg>
			<!--.................主体内容....................-->
			<div class="commodityMess" style="padding-top: 0;">
				<!--.................标题....................-->
				<div class="clearfix mb-20">
					<p class="float-l f18 font-b color-3">商品信息</p>
				</div>
				<!--.................查看信息的内容，在组件里....................-->
				<checkProducts :checkProduct="onlyProductMess"></checkProducts>
			</div>
		</el-dialog>

		<el-dialog :visible.sync="categoryDialog" :title="dialogTitle" size="tiny" custom-class="categoryDialog" :close-on-click-modal="false">
			<productClassify @categorys="categorys" :type="classifyType" :checkStyle="false" :Classify="storeClassify" :classfyId="classifyName">
				<div class="categorylabel" slot="header">
					<!--................选中的分类信息..............-->
					<span class="label_item" v-for="(item,index) in classifyName">
		        		{{item.name}}
		        		<svg width="12" height="12" @click="deleteCategorys(index,classifyName)" class="btn_delete">
		        			<use xlink:href="#delete"/>
		        		</svg>
        			</span>
				</div>
			</productClassify>

			<span slot="footer" class="dialog-footer">
		       <el-button type="primary" @click="setProduct">保存</el-button>
		       <el-button @click="categoryDialog = false">取消</el-button>
    		</span>
		</el-dialog>
		<div class="g-content" v-if="!isEdited">
			<div class="buttons">
				<el-button class="store-button2  mb-20" @click="batchCategory">
					<i class="iconfont icon-fenlei f12"></i>
					<span>批量分类</span>
				</el-button>				
				<search v-on:searchMthod="search" v-on:emptyMthod="empty" v-on:searchCondition="searchCondition"  ref="isShow">
					<template>
						<div class="condition">
							<span class="f12 color-3">商品价格:</span>
							<input type="number" v-model.number="searchMess.minPrice" /> 到 <input type="number" v-model.number="searchMess.maxPrice" />
						</div>
						<div class="classify ">
							<span class="f12 color-3">店铺中分类:</span>
							<el-select v-model="searchMess.classifyId" filterable placeholder="请选择" >
								<el-option v-for="(item,index) in storeClassify" :key="index" :value="item.id" :label="item.shop_category_name" :class="item.level===1?'color':''"> </el-option>
							</el-select>
						</div>
						<div class="condition">
							<span class="f12 color-3">创建时间:</span>
							<el-date-picker v-model="searchMess.minPubTime" type="date" placeholder="选择日期" :editable="false"> </el-date-picker> 到
							<el-date-picker v-model="searchMess.maxPubTime" type="date" placeholder="选择日期" :editable="false"> </el-date-picker>
						</div>
						<div class="classify ">
							<span class="f12 color-3">商品状态:</span>
							<el-select v-model="searchMess.statused" filterable placeholder="请选择">
								<el-option v-for="(item,index) in statusList" :key="index" :value="item.status" :label="item.value"> </el-option>
							</el-select>
						</div>
					</template>
				</search>
			</div>
			
			<el-table :data="categoryList.data" style="width: 100%" @selection-change="handleSelectionChange" :empty-text="emptyText" @sort-change="sortChange">
				<el-table-column type="selection" width="40"> </el-table-column>
				<el-table-column prop="images" width="74">
					<template slot-scope="props">
						<img :src="props.row.images[0].image_url" alt="" class="view_img">
					</template>
				</el-table-column>
				<el-table-column prop="product_name" label="商品名称" width="305">
					<template slot-scope="props">
						<div class="product_name" @click="checkProduct(props.$index)">{{props.row.product_name}}</div>
					</template>
				</el-table-column>
				<el-table-column prop="product_price_yuan.min" label="价格" sortable="custom" width="140">
					<template slot-scope="props">

						<span v-if="props.row.product_price_yuan.min==props.row.product_price_yuan.max " class="product_price">
					         {{props.row.product_price_yuan[0]}}
					    </span>
						<span v-else class="product_price">
					        {{props.row.product_price_yuan.min}} - {{props.row.product_price_yuan.max}}
					    </span>

					</template>
				</el-table-column>
				<el-table-column prop="shop_categorys" label="所属分类" width="220">
					<template slot-scope="scope">
						<div v-if='scope.row.shop_categorys.length>0'>
							<p>{{scope.row.shop_categorys[0].shop_category_name}}</p>
							<div v-if='scope.row.shop_categorys.length>1'>
								<p class="toggle" @click="toggleShow(scope.$index)">更多分类 <img src="../../assets/image/xiala.png" width="10" height="10"></p>
								<ul :class="{categoryBox:showIndex===scope.$index} ">
									<li v-if="index>0" v-for="(value,index) in scope.row.shop_categorys">{{value.shop_category_name}}</li>
								</ul>
							</div>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="created_at" label="创建时间" sortable="custom" width="152"></el-table-column>
				<el-table-column prop="status" label="状态" width="152">
					<template slot-scope="scope">
						<span v-if='scope.row.status=="on"'>出售中</span>
						<span v-else class="color-7F">仓库中</span>
					</template>
				</el-table-column>
				<el-table-column prop="shop_categorys" label="操作" width="116">
					<template slot-scope="scope">
						<el-button type="text" size="small" v-if='scope.row.shop_categorys.length>0' @click="editCategorys(scope.row)">
							编辑分类
						</el-button>
						<el-button type="text" size="small" v-if='scope.row.shop_categorys.length<=0' @click="editCategorys(scope.row)">
							添加分类
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination v-show="total" @current-change="handleCurrentChange" :current-page.sync="shopMess.page" :page-size="shopMess.per_page" layout="total, prev, pager, next" 
				:total="total" class="mt-20">
				
			</el-pagination>
		</div>
		<div v-else>
		</div>
	</div>
	</div>
</template>

<script>
	import Navbar from "@/components/commodity/Navbar"
	import search from '@/components/commodity/search'
	import storeClassify from '@/utils/storeClassify'
	import commodityMethod from '@/utils/commodity'
	import productClassify from '@/components/myStore/productClassify'
	import checkProducts from "@/components/commodity/checkProducts"
	import onOffProd from "@/utils/onOffPro"
	import {checkProduct,SaveShopClassifyList,setProductsCategory,setOnlyProductsCategory} from "@/api/commodity"

	export default {
		name: "category",
		data() {
			return {
				arr: ["分类二", "分类一"],
				classifyType: "多选",
				classifyName: [],
				showIndex: "",
				total: parseInt(""),
				list: [],
				statusList: [{
					"status": "on",
					"value": "出售中"
				}, {
					"status": "off",
					"value": "仓库中"
				}],
				isEdited: false,
				dialogVisible: false,
				categoryDialog: false,
				dialogTitle: "添加分类",
				index: 0,
				emptyText: "仓库中未发现商品记录",
				changeList: {
					products: [],
					shop_categorys: []
				},
				changeProduct: {
					product_id: "",
					shop_categorys: []
				},
				searchMess:{
					classifyId: "",
					statused: "on",
					minPrice: "",
					maxPrice: "",
					minPubTime: "",
					maxPubTime: "",
				},
				shopMess: {
					mall_id: "",
					shop_id: "",
					per_page: 20,
					page: 1,
					search: {
						status:"on"
					}
				},
				categoryList: {},
				onlyProductMess: {},
				shop_category:[],
				searchCon:{},
				deleteAttrApi:["product_price_yuan","shop_category_id","create_time","status"],
				isEmptyError:false,
				isRturn:{},
				order:{}
			}
		},
		mixins: [storeClassify, commodityMethod,onOffProd],
		created() {
			//我的店铺商品数据
			this.searchMethods();			
			let mall_id = this.$store.getters.getMall_id;
			let shop_id = this.$store.getters.getShop_id;
			this.$set(this.shopMess, "mall_id", mall_id);
			this.$set(this.shopMess, "shop_id", shop_id);		
		},
		components: {
			Navbar,search,productClassify,checkProducts			
		},
		methods: {
			closeSearch(){
				this.$refs.isShow.closeSearch()
			},
			initStoreClassify() { //初始化数据
				for(let val of this.storeClassify) {
					val.checked = false;
				}
			},
			isChecked(data){
				//传到子集时判断是否事先被选中
				for(let val of this.storeClassify){
					if(data.includes(val.id)){
						val.checked=true
					}
				}
			},
			//点击编辑、添加分类
			editCategorys(product) {
				this.$set(this.changeProduct, "product_id", product.id);
				this.shop_category=product.shop_categorys;
				this.categoryDialog = true;
				this.initStoreClassify();
				this.dialogTitle = "添加分类";
				this.classifyName = [];
				//分类没有那么就直接返回
				if(this.shop_category.length<=0) {
					return;
				};			
				this.dialogTitle = "编辑分类"
				let newArr = [];
			    if (this.shop_category.length != 0 && this.storeClassify != 0) {
			      for (let key in this.shop_category) {		      
			        if (this.shop_category[key].is_final != 0 && this.shop_category[key].level != 1) {
			          let index = "";
			          for (let i = 0; i < this.storeClassify.length; i++) {
			            if (this.storeClassify[i].id == this.shop_category[key].shop_category_id) {
			              this.storeClassify[i].checked = true;
			              index = i;
			            }
			          }
					newArr.push({
			            id: this.shop_category[key].shop_category_id,
			            index: index,
			            name: this.shop_category[key].shop_category_name
			          })
			        }
			      }
			    }
	    
				//传到子集时要被选中
				this.classifyName = newArr;
				var filters=this.classifyName.map(item=>item.id);
				//事先选中的状态
				this.isChecked(filters)
			},
						
			//批量分类按钮
			batchCategory() {
				if(this.changeList.products.length == 0) {
					return;
				}
				this.categoryDialog = true;
				this.dialogTitle = "批量分类"
				this.classifyName = [];
				this.initStoreClassify();
			},
			deleteCategorys(index, arr) { //删除分类
				if(this.storeClassify.length != 0) {
					let data = this.storeClassify[arr[index].index];
					data.checked = false;
					this.$set(this.storeClassify, arr[index].index, data);
				}
				arr.splice(index, 1)
			},
			categorys(data) {
				this.classifyName = data;
			},
			toggleShow(index) {
				if(index === this.showIndex) {
					this.showIndex = ""
				} else {
					this.showIndex = index;
				}
			},
			//获取商品链接列表的方法（共用）
			searchCondition(val) {
				if(val!==undefined){
					this.shopMess.search=Object.assign({},this.shopMess.search,val);	
				}else{
					delete this.shopMess.search.product_name;
				}
				this.emptyText = "未搜索到相关商品";
				//清空排序样式
				if(JSON.stringify(this.order)!=="{}"){
					this.order.column.prop="";				
					this.order.column.order="";
				};
				this.searchMethods();
			},
			search() { //筛选商品
				this.switchShow = false;
				this.NumberMenthods("maxPrice","minPrice","product_price_yuan","最高价格小于最低价格");
				if(this.searchMess.classifyId != "") {
					this.searchCon.shop_category_id = this.searchMess.classifyId
				};
				this.timeMenthods("minPubTime","maxPubTime","create_time","最小时间小于最大时间");
				if(this.searchMess.statused != "") {
					this.searchCon.status = this.searchMess.statused;
				};
				if(this.isEmptyError) {
					return;
				};
				console.log("this.searchCon:",this.searchCon)
				this.shopMess.search=Object.assign({},this.shopMess.search,this.searchCon)
				this.emptyText = "未搜索到相关商品";
				//清空排序样式
				if(JSON.stringify(this.order)!=="{}"){
					this.order.column.prop="";				
					this.order.column.order="";
				};
				this.searchMethods()
			},
			empty() { //清空
				let arr=["classifyId","statused","minPrice","maxPrice","minPubTime","maxPubTime"];
				this.clear(arr,this.searchMess);
				//清除传给Api的条件	
				if(this.shopMess.search!==undefined){
					this.deleteAttrApi.map(item =>{
						if(this.shopMess.search[item]!==undefined){
							return delete this.shopMess.search[item]
						};
					})
				};
				delete this.searchCon.shop_category_id;
				this.searchCon.status="all";
				this.$set(this.shopMess,"search",{status:"all"})
				//清空排序样式
				if(JSON.stringify(this.order)!=="{}"){
					this.order.column.prop="";				
					this.order.column.order="";
				};
				//清空然后掉接口重新拉取列表
				this.searchMethods()
			},
			handleSelectionChange(list) { //选中
				let arr = [];
				for(let val of list) {
					arr.push({
						product_id: val.id
					})
				};
				this.$set(this.changeList, "products", arr);
			},

			checkProduct(index) {
				this.index = index;
				let list = this.categoryList.data; 
				let product_id = list[index].id;
				checkProduct(product_id)
					.then(({data}) => {				
						if(this.dialogVisible == false) {
							this.dialogVisible = true;
						}
						this.onlyProductMess = data;
						console.log(data);
					})
					.catch(({response: {data}})=>{
						 this.$message.error(data.errorcmt);
					})	
			},

			nextProduct() {
				if(this.index < this.categoryList.data.length - 1) {
					this.index++;
					this.checkProduct(this.index)
				};

			},
			prevProduct() {
				if(this.index > 0) {
					this.index--;
					this.checkProduct(this.index)
				};
			},
			//分类中的保存
			setProduct() {					
				if(this.classifyName.length == 0) {
					this.$message("请选择分类")
					return;
				}
				let idArr = [];
				for(let val of this.classifyName) {
					idArr.push({
						shop_category_id: val.id
					})
				};		
				this.$set(this.changeList, "shop_categorys", idArr);
				this.$set(this.changeProduct, "shop_categorys", idArr);
				//批量分类中的按钮
				if(this.dialogTitle == "批量分类") {	
					setProductsCategory(this.changeList)
					.then(({data}) => {	
						this.categoryDialog = false;
						this.searchMethods();			
					}).catch(({response: {data}})=>{
						 this.$message.error(data.errorcmt);
					})	
					return;
				}
				
				//编辑、添加分类中的保存按钮	
				setOnlyProductsCategory(this.changeProduct)
				.then(({data}) => {	
					this.categoryDialog = false;
					this.searchMethods();			
				}).catch(({response: {data}})=>{
					 this.$message.error(data.errorcmt);
				})	
			}
		}
	}
</script>

<style lang="scss">
	.category {
		.Classify {
			min-height: 300px!important;
		}
		.el-table{
			overflow:visible;
			.el-table__body-wrapper{
				overflow: inherit;
			}
		}
		.btn_delete {
			margin-left: 10px;
			cursor: pointer;
		}
		.toggle {
			color: #7F7F7F;
			cursor: pointer;
			position: relative;
		}
		.toggle+ul {
			display: none;
		}
		.toggle+.categoryBox {
			display: block;
			position: absolute;
			background: #fff;
			width: 184px;
			box-shadow: 0 0 6px 0 rgba(0, 0, 0, 0.04), 0 2px 4px 0 rgba(0, 0, 0, 0.12);
			border-radius: 2px;
			z-index: 1000;
			padding: 10px;
		}
		.check {
			.el-dialog__header{
				padding:0;
			}
		}

		.el-dialog__body {
			padding:20px;
			.Classify {
				border-bottom: 1px solid #E9EEF2;
			}
		}
	}
</style>
